package com.ukao.steward.ui.valetRunners.storage;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.StorageListBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.ClearEditText;
import com.ukao.steward.widget.StateImageView;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.steward.R.id.title_layout;


public class StorageFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.edit_text)
    ClearEditText editText;
    @BindView(R.id.sweep_btn)
    StateImageView sweepBtn;
    @BindView(R.id.search_btn)
    Button searchBtn;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Unbinder unbinder;


    public static StorageFragment newInstance(String param1, String param2) {
        StorageFragment fragment = new StorageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected void initView() {
        setStatusBarTintColor(R.color.normal_blue);
        title.setText("入库");
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        KeyBoardUtil.showKeyboard(editText);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_storage, container, false);
        unbinder= ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();
        initListener();
    }

    @Override
    protected void initListener() {
        super.initListener();
        editText.setOnEditorActionListener(mOnEditorActionListener);
    }

    private TextView.OnEditorActionListener mOnEditorActionListener = (v, actionId, event) -> {
        if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
            queryCodeEdit();

        }
        return false;
    };

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setStatusBarTintColor(R.color.normal_blue);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.back_btn, R.id.sweep_btn, R.id.search_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.sweep_btn:
                Intent mIntent = ActivityUtils.JumpToBundleActivity(_mActivity);
                startActivityForResult(mIntent, Constant.REQUEST_CODE);

                break;
            case R.id.search_btn:
                queryCodeEdit();
                break;
        }
    }

    void queryCodeEdit() {
        String      keywords =getText(editText);
        if (keywords.isEmpty()){
            return;
        }
        queryCode(keywords);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    String code = data.getStringExtra(Constant.ARG_PARAM1);
                    editText.setText(code);
                    queryCode(code);
                    break;
            }
        }

    }

    /**
     *   订单、运单码
     * @param keywords
     */
    public void queryCode(String keywords ) {
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("keywords", keywords);
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().queryCode (Constant.createParameter(mHashMap)),
                new ApiCallback<StorageListBean>() {
                    @Override
                    public void onSuccess(StorageListBean model) {
                        if (model.getHttpCode() == 200) {
                             editText.setText("");
                            if (model.getData().getIsStore()==1){
                                start(SelectStoreFragment.newInstance(keywords, ""),SINGLETASK);
                            }else  if (!CheckUtils.isEmpty(model.getData().getStoreId())){

                                start(StorageListFragment
                                        .createBuilder()
                                        .orderNo(keywords)
                                        .storeId(model.getStoreId()).build()
                                        ,SINGLETASK);

                            }


                        } else {
                            T.show(model.getMsg());

                        }


                    }


                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }

                });
    }

}
